import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { Button,  FormInstance, message, Popconfirm} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import CreateForm from './components/CreateForm';
import { addApi, deleteApi, treeApi, flatApi } from './services';




const Page: React.FC<unknown> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const editFormRef = useRef<FormInstance>();
  const [currentItem, setCurrentItem] = useState<any>(null)

  const deleteItem = async (id: number) => {
    const res = await deleteApi(id)
    if (res.code == 200) {
      message.success("删除成功")
      actionRef.current?.reload()
    }
  }

  const columns: ProColumns<any>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      hideInForm:true

    },
    {
      title: '名称',
      dataIndex: 'name',
      tip: '名称是唯一的 key',
      sorter: true,

      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
    },
    {
      title: '路径',
      dataIndex: 'path',
      valueType: 'text',
      sorter: true,

    },
    {
      title: 'parentId',
      dataIndex: 'parentId',
      valueType: 'digit',
      sorter: true,

    },
    {
      title: '描述',
      dataIndex: 'comment',
      valueType: 'text',


    },
    

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>

          <Popconfirm
            title="删除"
            description="确定删除当前分类？"

            onConfirm={() => { deleteItem(record.id) }}
          >
            <Button danger>删除</Button>
          </Popconfirm>


        </>
      ),
    },
  ];

  useEffect(() => {
    if (createModalVisible && currentItem) {
      editFormRef.current?.setFieldsValue(currentItem)
    } else if (createModalVisible) {
      editFormRef.current?.resetFields()
    }
  }, [createModalVisible])

  return (
    <PageContainer
      header={{
        title: '文章分类',
      }}
    >
      <ProTable<any>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => handleModalVisible(true)}
          >
            新建
          </Button>,
          <Button
            key="2"
            type="primary"
            onClick={() => treeApi()}
          >
            获取树形菜单
          </Button>,
        ]}
        request={async (params, sorter, filter) => {
          console.log(params, sorter, filter);
          let orderBy = 'id desc';
          const objArr = Object.keys(sorter);
          // 有排序字段,暂时支持单字段
          if (objArr.length > 0) {
            const file = objArr[0];
            if (sorter[file] == "descend") {
              orderBy = `${file} desc`
            } else {
              orderBy = `${file} asc`
            }
          }

          const { current, pageSize, ...other } = params
          const { data, code } = await flatApi({
            page: current,
            pageSize: pageSize,
            orderBy,
            ...other

          });
          return {
            data: data || [],
            success: code == 200,
            // total:data.total||0
          };
        }}
        columns={columns}
        pagination={{
          pageSize: 10,
          onChange: (page) => console.log(page),
        }}
      />
      <CreateForm
        onCancel={() => { handleModalVisible(false); setCurrentItem(null) }}
        modalVisible={createModalVisible}
      >
        <ProTable
          onSubmit={async (value) => {


            const hide = message.loading("正在提交！")
            const subData = {

              ...value
            }
            if (currentItem) {
              subData.id = currentItem.id
            }

            const res = await addApi(subData)
            hide()
            if (res.code != 200) {
              return false
            } else {
              handleModalVisible(false);
              setCurrentItem(null)
              if (actionRef.current) {
                actionRef.current.reload();
              }
              return true
            }

          }}
          rowKey="id"
          type="form"
          formRef={editFormRef}
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default Page;
